define(function(require) {
	// var $ = require("jquery");
	var justep = require("$UI/system/lib/justep");
	require("cordova!cordova-plugin-app-version");
	var fn = require("$UI/ls_common/fn");
	var Model = function() {
		console.log("login.js Model");
		this.callParent();
		this.login_error = justep.Bind.observable(false);
		this.on_input = justep.Bind.observable(false);

	};

	Model.prototype.modelLoad = function(event) {
		console.log("login.js modelLoad");
		var self = this;
		if (window.cordova && window.cordova.getAppVersion) {
			window.cordova.getAppVersion.getVersionNumber(function(result) {
				self.getElementByXid("VersionSpan").innerHTML = "版本:" + result;
				self.checkUpdata(result);
			});
		}
		this.checkNewVersion(window.app.updataJson_Url);
	};

	Model.prototype.success = function(result) {
		console.log("login.js success");
		result;// 这个result就是版本号
		// alert(result);
		// that.getElementByXid("VersionLabel").innerHTML = result;
	};
	Model.prototype.error = function() {
		console.log("login.js error");
		justep.Util.hint("版本获取失败");
	};

	Model.prototype.LoadLocalUserName = function() {
		console.log("LoadLocalUserName()");
		fn.SqliteStorage.getItem("username", this.updata_callback, this);
		fn.SqliteStorage.getItem("password", this.updata_callback, this);
	};
	Model.prototype.updata_callback = function(key, val, caller_x5_model) {
		console.log("update_cllback()");

		if (key == "username")
			caller_x5_model.comp("userlogin").setValue("username", val);
		if (key == "password")
			caller_x5_model.comp("userlogin").setValue("password", val);
	};

	Model.prototype.modelParamsReceive = function(event) {
		console.log("login.js modelParamsReceive");
		console.log("清空输入框和错误提示等3");
		this.login_error.set(false);
		this.on_input.set(false);
		if (justep.Browser.isX5App) {
			this.LoadLocalUserName();
		} else {
			this.comp("userlogin").setValue("username", "15124083245");
			this.comp("userlogin").setValue("password", "4");
			// this.comp("userlogin").setValue("username", "yanggao");
			// this.comp("userlogin").setValue("password", "123456");
//			this.login_buttonClick(event);
		}

	};

	Model.prototype.content1Active = function(event) {
		console.log("login.js content1Active");
	};

	Model.prototype.login_buttonClick = function(event) {
		var self = this;
		console.log("登陆按钮Click");
		this.comp("LoadingPopOver").show();

		$.ajax({
			type : "POST",
			url : require.toUrl(window.app.HNLB_appConfigSever),
			data : {
				'data' : JSON.stringify({
					username : this.comp("userlogin").val("username"),
					password : this.comp("userlogin").val("password")
				})
			},
			dataType : 'json',
			async : false,
			cache : false,
			timeout : 10000, // 请求超时时间
			success : function(res) {
				console.log(res);
				window.app.base_url = res[0].Url + "/APP/";
				window.app.updateUrl = res[0].Url + "/appdownload/";
				window.app.updataJson_Url = window.app.updateUrl + "appMetadata.json";
				console.log(window.app.updataJson_Url);
				var api_url = "";
				if (window.app.LoginType == "Sales")
					api_url = window.app.base_url + window.app.UserApi;
				if (window.app.LoginType == "Factory")
					api_url = window.app.base_url + window.app.UserCJApi;
				var data1 = {};
				data1.username = self.comp("userlogin").val("username");
				data1.password = self.comp("userlogin").val("password");
				if (window.app.base_url.length < 1) {
					self.comp("LoadingPopOver").hide();
					justep.Util.hint("服务器出现异常，请联络管理员。");
					return;
				}
				$.ajax({
					type : "POST",
					url : require.toUrl(api_url),
					data : {
						'data' : JSON.stringify(data1)
					},
					dataType : 'json',
					async : true,
					cache : false,
					timeout : 2600, // 请求超时时间
					success : function(res) {
						console.log(res);
						console.log(data1);
						if (res[0].errno !== undefined) {
							self.comp("LoadingPopOver").hide();
							self.login_error.set(true);
							justep.Util.hint(res[0].msg);
							return;
						}
						window.app.username = data1.username;
						window.app.password = data1.password;

						if (justep.Browser.isX5App) {
							fn.SqliteStorage.setItem("username", data1.username);
							fn.SqliteStorage.setItem("password", data1.password);
						}
						var shell;
						if (window.app.LoginType == "Sales") {
							window.app.UserApi_ret = res[0];
							window.app.CtmType = res[0].CtmType;
							console.log(window.app.UserApi_ret);
							console.debug("切换到主界面1.");
							shell = justep.Shell.loadPage({
								url : require.toUrl('./Main.w')
							});
							shell.then(function() {
								console.log("页面已经加载完毕");
								self.comp("LoadingPopOver").hide();
								justep.Shell.showPage("Main", {
									'from' : 'Login'
								});
							}, function() {
								console.log("页面读取失败");
							});
						}
						if (window.app.LoginType == "Factory") {
							window.app.UserCJApi_ret = res[0];
							window.app.CtmType = res[0].CtmType;
							console.log(window.app.UserCJApi_ret);
							console.debug("切换到厂商界面.");
							shell = justep.Shell.loadPage({
								url : require.toUrl('Factory/FactoryMain.w')
							});
							shell.then(function() {
								console.log("页面已经加载完毕");
								self.comp("LoadingPopOver").hide();
								justep.Shell.showPage("FactoryMain", {
									'from' : 'Login'
								});
							}, function() {
								console.log("页面读取失败");
							});
						}
					},
					error : function(e) {
						self.comp("LoadingPopOver").hide();
						self.login_error.set(true);
						console.log("网络不通畅，登录失败。");
					}
				});
			},
			error : function(e) {
				self.comp("LoadingPopOver").hide();
				justep.Util.hint("服务器出现异常，请联络管理员。");
			}
		});

	};

	Model.prototype.VerBtnClick = function(event) {
		this.comp("updataWindowDialog").open({
			src : require.toUrl('./updata_windowdialog.w')
		});
	};

	Model.prototype.checkUpdata = function(now_version) {
		console.debug("checkUpdata()");
		var verJsonUrl = window.app.updataJson_Url;
		var self = this;
		console.debug(require.toUrl(verJsonUrl));
		var http = new window.plugin.HttpRequest();
		http.get(require.toUrl(verJsonUrl), {}, function(is_err, resdata) {
			if (is_err === null) {
				console.debug(resdata);
				if (resdata !== undefined) {
					var appMetadata = JSON.parse(resdata);
					console.debug(appMetadata.appInfo.androidApp.version);
					console.debug(appMetadata.appInfo.androidApp.downloadURL);

					if (appMetadata.appInfo.androidApp.version > now_version) {
						self.comp("updataWindowDialog").open({
							src : require.toUrl('./updata_windowdialog.w')
						});
					}
				}
			} else {
				justep.Util.hint(verJsonUrl);
			}
		});

	};
	Model.prototype.checkNewVersion = function(verJsonUrl) {
		var self = this;
		if (window.cordova === undefined) {
			// justep.Util.hint("检测到不是手机环境运行");
		} else {
			window.cordova.getAppVersion.getVersionNumber(function(result) {
				var appver = result;
				var http = new window.plugin.HttpRequest();
				http.get(require.toUrl(verJsonUrl), {}, function(is_err, resdata) {
					if (is_err === null) {
						console.debug(resdata);
						if (resdata !== undefined) {
							var appMetadata = JSON.parse(resdata);
							console.debug(appMetadata.appInfo.androidApp.version);
							console.debug(appMetadata.appInfo.androidApp.downloadURL);
							if (appver > appMetadata.appInfo.androidApp.version) {
								justep.Util.hint("有新版本可以升级");
								self.comp("updataWindowDialog").open({
									"src" : require.toUrl('$UI/ls_common/updata_win/updata_windowdialog.w'),
									"data" : window.app.updataJson_Url
								});
							}
						}
					}
				});
			});
		}
	};
	return Model;
});